/*
 *  region.cc
 *  wonderland-project
 *
 *  Created by Ben Nolan on 15/10/08.
 *  Copyright 2008 Nolan Consulting Limited. All rights reserved.
 *
 */

#include "region.h"
#include "wonderland.h"
#include "serialize.h"
#include "deserialize.h"
#include <Ogre.h>
#include <fstream>
#include <string>
#include "sync_manager.h"



namespace Wonderland{
	Ogre::Node::Listener* dirty_node_listener_;

	class NodeListener : public Ogre::Node::Listener{

	public:
		NodeListener::NodeListener(Wonderland::SyncManager *sync){
			sync_manager_ = sync;
		}
		
		void nodeUpdated(const Ogre::Node *node){
			sync_manager_->addNode((Ogre::SceneNode *) node);
		};
	
		void nodeDestroyed(const Ogre::Node *node){
		};

		void nodeAttached(const Ogre::Node *node){
		};

		void nodeDetached(const Ogre::Node *node){
		};
	private:
		Wonderland::SyncManager *sync_manager_;
		
	};
	
	void Region::save(std::string fn){
		std::fstream fs(fn.c_str(), std::fstream::out);
		fs << Wonderland::Serialize(getSceneManager()->getRootSceneNode());
		fs.close();
	}

	void Region::load(std::string fn){
		std::string xml = Wonderland::Utility::slurp(fn);
		Wonderland::Deserialize(xml, this);
	}

	Ogre::SceneNode* Region::createNode(std::string name){
		std::cout << "NODE CREATED" << std::endl;
		
		Ogre::Entity *ent = scene_manager_->createEntity(std::string(name) + "/Mesh", Ogre::SceneManager::PT_CUBE);
		ent->setMaterialName("html/colors/silver");

		Ogre::MeshPtr mesh = ent->getMesh();
		Ogre::Real height = mesh->getBounds().getSize().y;

		Ogre::SceneNode *node = getSceneManager()->getRootSceneNode()->createChildSceneNode(name);
		node->attachObject(ent);
		
		if(sync_manager_){
			node->setListener(dirty_node_listener_);
		}
		
		node->setScale(Ogre::Vector3(1.0 / height, 1.0 / height, 1.0 / height));
		
		return node;
	}

	void Region::setSyncManager(Wonderland::SyncManager* sync){
		sync_manager_ = sync;

		dirty_node_listener_ = new NodeListener(sync);
	}

}